#coding=utf-8
import gtk
from stockdb.misc import *
from cols import *

def cell_data_func( column, cell_renderer, model, iter_, user_data):
    
    col_index, ca = user_data
    v = model.get_value(iter_, col_index)
    
    if ca.coltype == 'str':
        cell_renderer.set_property("text", v)
    elif ca.coltype == 'int': 
        cell_renderer.set_property("text", '%i'%v)
    elif ca.coltype == 'float':
        if ca.is_colored:
            cell_renderer.set_property("foreground-set",True)
            if(v>0):cell_renderer.set_property('foreground',"red")
            else:cell_renderer.set_property('foreground',"green")
            
        if ca.is_percent:    
            cell_renderer.set_property("text", '%0.2f%%'%v)
        else:
            cell_renderer.set_property("text", '%0.2f'%v)    
        
date = '2008-03-20'

ss = sess.query(Stock).all()[:15]
data = []

for s in ss:
    td = s.find_td(date)
    if not td:continue
    
    p = td.price
    d = [date, s.name, s.code, p.jump, td.close, p.change, p.trade_rate]
    data.append(d)

################################################################################
columns = ['date', 'name', 'code', 'jump', 'close', 'change', 'trade_rate']

cas = []
for col in columns:
    cas.append(find_colattr(col))

#models
tps = [pytype2gtype[ca.coltype] for ca in cas]    
lt = gtk.ListStore(*tps)
for d in data:
    lt.append(d)

#views    
tv = gtk.TreeView(lt)

i = 0
for ca in cas:

    cell = gtk.CellRendererText()
    tc = gtk.TreeViewColumn(ca.colhead, cell)
    
    tc.set_cell_data_func( cell, cell_data_func, (i, ca))
    tc.set_sort_column_id(i)
    
    tv.append_column(tc)
 
    i = i + 1
    
window = gtk.Window()
window.set_default_size(500, 350)
sw = gtk.ScrolledWindow()
sw.add(tv)
window.add(sw)
window.show_all()

gtk.main()
